/* Copyright (C) 2007-2010 STS Soft

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

using System;
using System.IO;
using STSdb.Files;

namespace STSdb.Volumes
{
    /// <summary>
    /// Class is ThreadSafe
    /// </summary>
    public class MemoryVolume : IVolume
    {
        public readonly MemoryStream stream;

        public MemoryVolume(ulong quota)
        {
            Quota = quota;
            stream = new MemoryStream();
        }

        #region IFile Members

        public void Write(ulong position, byte[] buffer, int index, int count)
        {
            lock (stream)
            {
                if (position + (uint)count >= Quota)
                    throw new Exception("Reached quota limit.");
                
                stream.Seek(checked((long)position), SeekOrigin.Begin);
                stream.Write(buffer, index, count);
            }
        }

        public void Read(ulong position, byte[] buffer, int index, int count)
        {
            lock (stream)
            {
                stream.Seek(checked((long)position), SeekOrigin.Begin);
                stream.Read(buffer, index, count);
            }
        }

        public void Flush()
        {
            lock (stream)
                stream.Flush();
        }

        public void Close()
        {
            lock (stream)
                stream.Close();
        }

        public ulong Length
        {
            get
            {
                lock (stream)
                    return (ulong)stream.Length;
            }
        }

        public ulong Quota { get; private set; }

        #endregion
    }
}
